import os
import cv2
from plate_detection import detect_plate
from char_segmentation import segment_characters
from char_recognition import CharRecognizer


def main():
    # 获取当前脚本的目录
    current_dir = os.path.dirname(os.path.abspath(__file__))

    # 加载训练好的模型
    recognizer = CharRecognizer()
    model_path = os.path.join(current_dir, '..', 'models', 'svm_model.dat')
    recognizer.load_model(model_path)

    # 读取测试图像
    image_path = os.path.join(current_dir, '..', 'data', 'test', 'test_image.jpg')
    image = cv2.imread(image_path)

    if image is None:
        print(f"Unable to read image: {image_path}")
        return

    print("Image loaded successfully.")

    # 车牌定位
    plate_image = detect_plate(image)
    if plate_image is None:
        print("No license plate detected.")
        return

    print("License plate detected.")

    # 字符分割
    char_images = segment_characters(plate_image)

    print(f"Number of characters segmented: {len(char_images)}")

    # 字符识别
    plate_number = ''
    for i, char_img in enumerate(char_images):
        char = recognizer.predict(char_img)
        plate_number += char
        print(f"Character {i + 1} recognized as: {char}")

    print(f"Detected license plate: {plate_number}")


if __name__ == "__main__":
    main()